package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {
	private int port = 26678;
	private boolean run = true;
	private ServerSocket socket;

	public ArrayList<Client> clients = new ArrayList<Client>();

	private void start() throws Exception {
		if (System.console() == null) {
			// return;
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter port: ");
		String p = br.readLine();
		if (!p.equals("")) {
			port = Integer.parseInt(p);
		}

		socket = new ServerSocket(port);
		System.out.println("Server started on port " + port);

		new Thread(new Runnable() {
			public void run() {
				while (run) {
					try {
						if (!socket.isClosed()) {
							Socket s = socket.accept();
							addClient("Guest", s);
						}
					} catch (Exception e) {
					}
				}
			}
		}).start();

		while (run) {
			String s = br.readLine();
			if (!s.equals("")) {
				if (s.toLowerCase().equals("/stop")) {
					run = false;
					disconnect();
				} else {
					send("Server", s);
				}
			}
		}
	}

	private void addClient(String name, Socket socket) {
		clients.add(new Client(this, name, socket));
		System.out.println("Client joined from " + socket.getInetAddress().toString());
	}

	public void send(String name, String msg) {
		System.out.println("[" + name + "]: " + msg);
		for (int i = 0; i < clients.size(); i++) {
			clients.get(i).send(name, msg);
		}
	}

	private void disconnect() throws Exception {
		socket.close();
		for (int i = 0; i < clients.size(); i++) {
			clients.get(i).disconnect();
		}
	}

	public static void main(String[] args) {
		Server server = new Server();
		try {
			server.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
